package Controllers;

import Controllers.exceptions.IllegalOrphanException;
import Controllers.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entities.HdSetores;
import Entities.HdTipoUser;
import Entities.HdChamados;
import Entities.HdUsers;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Ferrari
 */
public class HdUsersJpaController implements Serializable {

    public HdUsersJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(HdUsers hdUsers) {
        if (hdUsers.getHdChamadosList() == null) {
            hdUsers.setHdChamadosList(new ArrayList<HdChamados>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            HdSetores coSetorUser = hdUsers.getCoSetorUser();
            if (coSetorUser != null) {
                coSetorUser = em.getReference(coSetorUser.getClass(), coSetorUser.getCoSetor());
                hdUsers.setCoSetorUser(coSetorUser);
            }
            HdTipoUser coTipoUser = hdUsers.getCoTipoUser();
            if (coTipoUser != null) {
                coTipoUser = em.getReference(coTipoUser.getClass(), coTipoUser.getCoTipoUser());
                hdUsers.setCoTipoUser(coTipoUser);
            }
            List<HdChamados> attachedHdChamadosList = new ArrayList<HdChamados>();
            for (HdChamados hdChamadosListHdChamadosToAttach : hdUsers.getHdChamadosList()) {
                hdChamadosListHdChamadosToAttach = em.getReference(hdChamadosListHdChamadosToAttach.getClass(), hdChamadosListHdChamadosToAttach.getCoChamado());
                attachedHdChamadosList.add(hdChamadosListHdChamadosToAttach);
            }
            hdUsers.setHdChamadosList(attachedHdChamadosList);
            em.persist(hdUsers);
            if (coSetorUser != null) {
                coSetorUser.getHdUsersList().add(hdUsers);
                coSetorUser = em.merge(coSetorUser);
            }
            if (coTipoUser != null) {
                coTipoUser.getHdUsersList().add(hdUsers);
                coTipoUser = em.merge(coTipoUser);
            }
            for (HdChamados hdChamadosListHdChamados : hdUsers.getHdChamadosList()) {
                HdUsers oldCoUserRespOfHdChamadosListHdChamados = hdChamadosListHdChamados.getCoUserResp();
                hdChamadosListHdChamados.setCoUserResp(hdUsers);
                hdChamadosListHdChamados = em.merge(hdChamadosListHdChamados);
                if (oldCoUserRespOfHdChamadosListHdChamados != null) {
                    oldCoUserRespOfHdChamadosListHdChamados.getHdChamadosList().remove(hdChamadosListHdChamados);
                    oldCoUserRespOfHdChamadosListHdChamados = em.merge(oldCoUserRespOfHdChamadosListHdChamados);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(HdUsers hdUsers) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            HdUsers persistentHdUsers = em.find(HdUsers.class, hdUsers.getCoUser());
            HdSetores coSetorUserOld = persistentHdUsers.getCoSetorUser();
            HdSetores coSetorUserNew = hdUsers.getCoSetorUser();
            HdTipoUser coTipoUserOld = persistentHdUsers.getCoTipoUser();
            HdTipoUser coTipoUserNew = hdUsers.getCoTipoUser();
            List<HdChamados> hdChamadosListOld = persistentHdUsers.getHdChamadosList();
            List<HdChamados> hdChamadosListNew = hdUsers.getHdChamadosList();
            List<String> illegalOrphanMessages = null;
            for (HdChamados hdChamadosListOldHdChamados : hdChamadosListOld) {
                if (!hdChamadosListNew.contains(hdChamadosListOldHdChamados)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain HdChamados " + hdChamadosListOldHdChamados + " since its coUserResp field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (coSetorUserNew != null) {
                coSetorUserNew = em.getReference(coSetorUserNew.getClass(), coSetorUserNew.getCoSetor());
                hdUsers.setCoSetorUser(coSetorUserNew);
            }
            if (coTipoUserNew != null) {
                coTipoUserNew = em.getReference(coTipoUserNew.getClass(), coTipoUserNew.getCoTipoUser());
                hdUsers.setCoTipoUser(coTipoUserNew);
            }
            List<HdChamados> attachedHdChamadosListNew = new ArrayList<HdChamados>();
            for (HdChamados hdChamadosListNewHdChamadosToAttach : hdChamadosListNew) {
                hdChamadosListNewHdChamadosToAttach = em.getReference(hdChamadosListNewHdChamadosToAttach.getClass(), hdChamadosListNewHdChamadosToAttach.getCoChamado());
                attachedHdChamadosListNew.add(hdChamadosListNewHdChamadosToAttach);
            }
            hdChamadosListNew = attachedHdChamadosListNew;
            hdUsers.setHdChamadosList(hdChamadosListNew);
            hdUsers = em.merge(hdUsers);
            if (coSetorUserOld != null && !coSetorUserOld.equals(coSetorUserNew)) {
                coSetorUserOld.getHdUsersList().remove(hdUsers);
                coSetorUserOld = em.merge(coSetorUserOld);
            }
            if (coSetorUserNew != null && !coSetorUserNew.equals(coSetorUserOld)) {
                coSetorUserNew.getHdUsersList().add(hdUsers);
                coSetorUserNew = em.merge(coSetorUserNew);
            }
            if (coTipoUserOld != null && !coTipoUserOld.equals(coTipoUserNew)) {
                coTipoUserOld.getHdUsersList().remove(hdUsers);
                coTipoUserOld = em.merge(coTipoUserOld);
            }
            if (coTipoUserNew != null && !coTipoUserNew.equals(coTipoUserOld)) {
                coTipoUserNew.getHdUsersList().add(hdUsers);
                coTipoUserNew = em.merge(coTipoUserNew);
            }
            for (HdChamados hdChamadosListNewHdChamados : hdChamadosListNew) {
                if (!hdChamadosListOld.contains(hdChamadosListNewHdChamados)) {
                    HdUsers oldCoUserRespOfHdChamadosListNewHdChamados = hdChamadosListNewHdChamados.getCoUserResp();
                    hdChamadosListNewHdChamados.setCoUserResp(hdUsers);
                    hdChamadosListNewHdChamados = em.merge(hdChamadosListNewHdChamados);
                    if (oldCoUserRespOfHdChamadosListNewHdChamados != null && !oldCoUserRespOfHdChamadosListNewHdChamados.equals(hdUsers)) {
                        oldCoUserRespOfHdChamadosListNewHdChamados.getHdChamadosList().remove(hdChamadosListNewHdChamados);
                        oldCoUserRespOfHdChamadosListNewHdChamados = em.merge(oldCoUserRespOfHdChamadosListNewHdChamados);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = hdUsers.getCoUser();
                if (findHdUsers(id) == null) {
                    throw new NonexistentEntityException("The hdUsers with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            HdUsers hdUsers;
            try {
                hdUsers = em.getReference(HdUsers.class, id);
                hdUsers.getCoUser();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The hdUsers with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<HdChamados> hdChamadosListOrphanCheck = hdUsers.getHdChamadosList();
            for (HdChamados hdChamadosListOrphanCheckHdChamados : hdChamadosListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This HdUsers (" + hdUsers + ") cannot be destroyed since the HdChamados " + hdChamadosListOrphanCheckHdChamados + " in its hdChamadosList field has a non-nullable coUserResp field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            HdSetores coSetorUser = hdUsers.getCoSetorUser();
            if (coSetorUser != null) {
                coSetorUser.getHdUsersList().remove(hdUsers);
                coSetorUser = em.merge(coSetorUser);
            }
            HdTipoUser coTipoUser = hdUsers.getCoTipoUser();
            if (coTipoUser != null) {
                coTipoUser.getHdUsersList().remove(hdUsers);
                coTipoUser = em.merge(coTipoUser);
            }
            em.remove(hdUsers);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<HdUsers> findHdUsersEntities() {
        return findHdUsersEntities(true, -1, -1);
    }

    public List<HdUsers> findHdUsersEntities(int maxResults, int firstResult) {
        return findHdUsersEntities(false, maxResults, firstResult);
    }

    private List<HdUsers> findHdUsersEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(HdUsers.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public HdUsers findHdUsers(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(HdUsers.class, id);
        } finally {
            em.close();
        }
    }

    public int getHdUsersCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<HdUsers> rt = cq.from(HdUsers.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
    public HdUsers findHdUsersByName(String name){
        EntityManager em = getEntityManager();
        
         List<HdUsers> list = em.createNamedQuery(HdUsers.findByNmUser , HdUsers.class)
            .setParameter("nmUser", name)
            .getResultList();
         
         if(list.size() > 0){
             return list.get(0);
         }else{
             return null;
         }
    }
    
}
